import React, { useState, Fragment } from 'react';
import { Button, Form, Input, Select } from 'antd';
import { MinusCircleOutlined } from '@ant-design/icons';

import DrawFormItemTitle from './DrawFormItemTitle';

const { Option } = Select;

const renderFormItems = (formItemOptions, field = {}) => {
  const renderFormItem = (option, idx) => {
    return (
      <Form.Item
        {...field}
        label={option.name}
        name={
          typeof field.name !== 'undefined' ? [field.name, option.formInputName] : option.formInputName
        }
        fieldKey={
          field.fieldKey
            ? [field.fieldKey, option.formInputName]
            : option.formInputName
        }
        rules={option.rules}
        key={idx}
      >
        {((option) => {
          if (option.isSelect) {
            return (
              <Select>
                {option.options.map((item) => (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            );
          } else if (option.isTags) {
            return (
              <Select mode="tags">
                {option.options.map((item) => (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            );
          } else if (option.isTextArea) {
            return <Input.TextArea />;
          } else {
            return <Input />;
          }
        })(option)}
      </Form.Item>
    );
  };
  return <Form.Item>{formItemOptions.map(renderFormItem)}</Form.Item>;
};

const renderFormList = (formItemOptions, name) => (
  <Form.List name={name}>
    {(fields, { add, remove }) => (
      <>
        {fields.map((field) => (
          <React.Fragment key={field.key}>
            {renderFormItems(formItemOptions, field)}
            <MinusCircleOutlined onClick={() => remove(field.name)} />
          </React.Fragment>
        ))}

        <Form.Item>
          <Button onClick={() => add()}>添加参数</Button>
        </Form.Item>
      </>
    )}
  </Form.List>
);

function DrawForm({ isDynamic, title, name, formItemOptions }) {
  const [status, SetStatus] = useState(false);
  const drawFormItemStatusChange = () => {
    SetStatus(!status);
  };

  return (
    <>
      <DrawFormItemTitle
        status={status}
        title={title}
        drawFormItemClick={drawFormItemStatusChange}
      />
      {status ? (
        <>
          {isDynamic ? renderFormList(formItemOptions, name) : renderFormItems(formItemOptions)}
        </>
      ) : null}
    </>
  );
}

DrawForm.propTypes = {};

export default DrawForm;
